public class Solution {
    public int maxTurbulenceSize(int[] nums) {
        int len = nums.length;

        if (len == 1) {
            return 1;
        }

        //以i为结尾的子数组是湍流数组的长度
        int[] dp = new int[len];

        dp[0] = 1;

        if (nums[1] == nums[0]) {
            dp[1] = 0;
        } else {
            dp[1] = 2;
        }

        for (int i = 2; i < len; i++) {
            if (nums[i] == nums[i - 1]) {
                dp[i] = 0;
            } else {
                dp[i] = (nums[i] > nums[i - 1] && nums[i - 1] < nums[i - 2]) || (nums[i] < nums[i - 1] && nums[i - 1] > nums[i - 2]) ? dp[i - 1] + 1 : 2;
            }
        }

        int ret = 0;

        for (int num : dp) {
            ret = Math.max(ret, num);
        }
        return ret;
    }
}
